/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.cezary.butler.walili.stats;

import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Czarek
 */
public class InstancesCounter implements IInstancesCounter {

    private static final Logger log = Logger.getLogger(InstancesCounter.class.getName());
    private Map<String, Integer> types = new TreeMap<String, Integer>();

    @Override
    public void countInstance(Object o) {
        if (o == null) {
            incrementInstance("null");
        } else {
            incrementInstance(o.getClass().getName());
        }
    }

    private synchronized void incrementInstance(final String type) {
        Integer counter = types.get(type);
        int c = (counter != null) ? counter.intValue() : 0;
        counter = ++c;
        types.put(type, c);
    }
    
    @Override
    public Map<String,Integer> getResults(){
        return Collections.unmodifiableMap(new TreeMap<String, Integer>(types));
    }
    
    @Override
    public void printStats(){  
        Iterator<Entry<String, Integer>> iter = types.entrySet().iterator();
        while(iter.hasNext()){            
            Entry<String, Integer> next = iter.next();
            log.log(Level.INFO,"Class {0} has been called out {1} times yet.",new Object[]{next.getKey(),next.getValue()});
        }
    }
}
